package A1_字符串;

public class LC_151翻转字符串里的单词_代码随想录方法 {
    public static void main(String[] args){
        String s="  hello world  ";
        System.out.println(reverseWords(s));
    }
    public static String reverseWords(String s) {
        s=reverse(s,0,s.length());//整体反转
        s=removeExtraSpaces(s);//去除多余空格
        //反转单个单词
        char[] c=s.toCharArray();
        int start=0;
        for(int end=0;end<=s.length();end++){
            if(end==s.length()||c[end]==' '){
                s=reverse(s,start,end);
                start=end+1;
            }
        }
        return s;
    }
    //反转
    public static String reverse(String s,int start,int end){
        StringBuilder str=new StringBuilder(s);
        StringBuilder str1= new StringBuilder(str.substring(start, end));
        str1=str1.reverse();
        str=str.replace(start,end,String.valueOf(str1));
        return String.valueOf(str);
    }
    //去除多于空格
    public static String removeExtraSpaces(String s){
        char[] c=s.toCharArray();
        int slow=0;
        for(int fast=0;fast<s.length();fast++){
            if(c[fast]!=' '){
                if(slow!=0)
                    c[slow++]=' ';
                while(fast<s.length() && c[fast]!=' '){
                    c[slow]=c[fast];
                    fast++;
                    slow++;
                }
            }
        }
        s=String.valueOf(c);
        StringBuilder str=new StringBuilder(s);
        str= new StringBuilder(str.substring(0, slow));
        return String.valueOf(str);
    }
}
